import React, { useState, useEffect } from 'react';
// import GoEasy from 'goeasy';
import styles from './chat.module.scss'
import { VolumeO ,createFromIconfontCN} from '@react-vant/icons'
import { NoticeBar,NavBar ,Toast } from 'react-vant'
import {useNavigate, useSearchParams} from 'react-router-dom'
import dayjs from 'dayjs';
import calendar from 'dayjs/plugin/calendar'
import http from '../../http';
dayjs.extend(calendar)
export default function ChantRoom() {
  const navigate=useNavigate()
   const IconFont = createFromIconfontCN('//at.alicdn.com/t/c/font_4410449_8qs8w05dkv4.js');
  const [messages, setMessages] = useState<any>([]);
  const [content, setContent] = useState('');
  //地址栏参数
   const [SearchParams]=useSearchParams()
    const doctorId = SearchParams.get("doctorId") as string;
  const recordId = SearchParams.get("recordId") as string;
  const doctorName = SearchParams.get("doctorName") as string;
  const imagePic = SearchParams.get("imagePic") as string;

 
   
  useEffect(() => {
    connectGoEasy();
    subscribe();
  }, []);

  ///查看历史消息
  useEffect(()=>{
      //历史消息接口
     http.get('/health/user/inquiry/verify/v1/findInquiryRecordList',{params:{inquiryId:recordId,page:1,count:20}}).then((res:any)=>{
      // console.log(res.result);
      setMessages(res.result.reverse())
      // setMessages(res.result)
     })
  },[messages])

  const connectGoEasy = () => {
    window.goEasy.connect({
      onProgress: (attempts: any) => {
        // console.log("GoEasy is connecting", attempts);
      },
      onSuccess: () => {
        // unshiftMessage("连接成功");
        // console.log("GoEasy connect successfully.");
      },
      onFailed: (error: any) => {
        // unshiftMessage("Failed to connect GoEasy, code:" + error.code + ",error:" + error.content);
      },
    });
  };

  const subscribe = () => {
    window.goEasy.pubsub.subscribe({
      channel: `my_channel_${recordId}`,
      onMessage: (message: any) => {
        console.log(message.content,'message')
        unshiftMessage({...JSON.parse(message.content),direction: JSON.parse(message.content).role === 'user' ? 1 : 2 });
      },
      onSuccess: () => {
        // unshiftMessage("订阅成功.");
      },
      onFailed: (error: any) => {
        // unshiftMessage("订阅失败，错误编码：" + error.code + " 错误信息：" + error.content);
      },
    });
  };

  const sendMessageByEnter = (event: any) => {
    if (event.key === "Enter") {
      event.preventDefault();
      sendMessage();
    }
  };

  const sendMessage = () => {
    if (content.trim() !== "") {
      window.goEasy.pubsub.publish({
        channel: `my_channel_${recordId}`,
        message: JSON.stringify({content:content, role: 'user', userHeadPic: '', askTime: new Date().getTime(), msgType: 1}),
        onSuccess: () => {
          let putContent={
            inquiryId:recordId,
            content:content,
            type:"1",
            doctorId:doctorId
          }
          http.post('/health/user/inquiry/verify/v1/pushMessage',putContent,{
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
             setContent("");
          
          
          // console.log("send message success");
        },
        onFailed: (error: any) => {
          // unshiftMessage("消息发送失败，错误编码：" + error.code + " 错误信息：" + error.content);
        },
      });
    }
  };

  const unshiftMessage = (content: any) => {
    setMessages((prevMessages:any) => [ ...prevMessages,content]);
  };

  const inputValChange = (e: any) => {
    setContent(e.target.value);
  };
  return (
    <div className={styles.MaxBox}>
         <NavBar
      title="姓名"
      onClickLeft={() => navigate('/doctorList')}
    />
    
        <NoticeBar
        scrollable 
      leftIcon={<VolumeO />}
      text='请注意聊天内容的规范,文明用语,切勿输入敏感词汇。'
    />
      <div className={styles.index}>
        <div className={styles.container}>
          <div className={styles.header}>
          </div>
          
          <div className={styles.messageContainer}>
            <div className={styles.messageContent}>
              {messages.map((item:any, index:any) =>
                <div className={styles.EveryMessage} key={index}>

                {
                  !index || item.askTime - messages[index - 1].askTime > 5 * 60*1000 ? <div className={styles.MessageTime}>{dayjs(item.askTime).calendar(null,{
                    sameDay: ' HH:mm', // The same day ( Today at 2:30 AM )
                    nextDay: '[Tomorrow]', // The next day ( Tomorrow at 2:30 AM )
                    nextWeek: 'dddd', // The next week ( Sunday at 2:30 AM )
                    lastDay: '[昨天]', // The day before ( Yesterday at 2:30 AM )
                    lastWeek: '[上周] dddd', // Last week ( Last Monday at 2:30 AM )
                    sameElse: 'YYYY/DD/MM HH:mm' // Everything else ( 7/10/2011 )
                   })}</div> : ''
                }
                <div key={index} className={`${item.direction === 2?styles.messageLeft : styles.messageRight}`}>

                    <div className={styles.headSculpture}></div>
                     <div className={styles.Message}>{item.content}</div>
                  
                </div>
                </div>
                
              )}
            </div>
          </div>
          
          <div className={styles.sendBox}>
              <IconFont name='icon-yuyin' className={styles.voice}></IconFont>
            <input value={content} onChange={inputValChange} onKeyDown={sendMessageByEnter}/>
             <IconFont name='icon-yuyin' className={styles.voice}></IconFont>
            <span onClick={sendMessage}>发送</span>
          </div>
        </div>
      </div>
    </div>
  )
}
